package com.gc.controller;


import com.gc.service.EmailService;
import com.gc.service.GcAuthCodeService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
@RequestMapping("/api/code")
public class AuthCodeController {

    @Autowired
    private GcAuthCodeService gcAuthCodeService;

    @Reference
    private EmailService emailService;


    @Value("${config.email.templates.checkcode.content}")
    private String emailContent;
    /**
     * 生成验证码并发送到邮箱，成功true，失败false
     * /code/create/{email}
     * @param email
     * @return
     */
    @GetMapping("/create/{email}")
    public boolean createAuthCode(@PathVariable("email") String email) {
        System.out.println("========获取验证码=======");
        //1.生成验证码
        String code = getRandomCode();
        gcAuthCodeService.createAuthCode(email, code);
        String message = String.format(emailContent, code);
        //2.发送到邮箱
        return emailService.sendEmail(email, code,message);
    }

    /**
     * 校验验证码是否正确
     * 0-正确，1-错误，2-超时
     * @param email
     * @param code
     * @return
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validateAuthCode(@PathVariable("email") String email, @PathVariable("code") String code) {
        int i = gcAuthCodeService.validateAuthCode(email, code);
        return i;
    }

    /**
     * 随机生成6位数
     * @return
     */
    private String getRandomCode() {
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
        return result;
    }

}
